from pathlib import Path
from tkinter import *
from tkinter import messagebox
from gui.main_window.main import main_Window
from gui.login import notpassword
import pymysql
import configparser
import hashlib
import sys

OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./img")

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)
# 连接数据库
class MysqlSearch(object):
    def __init__(self):
        self.get_conn()

    def get_conn(self):
        try:

            # 用ini配置mysql数据库
            self.config = configparser.ConfigParser()
            self.config.read_file(open(f"{OUTPUT_PATH}/mysql.ini", encoding="utf-8", mode="rt"))

            self.conn = pymysql.connect(
                host=self.config.get('mysql', 'host'),  # 连接名称，默认127.0.0.1
                user=self.config.get('mysql', 'user'),  # 用户名
                passwd=self.config.get('mysql', 'passwd'),  # 密码
                port=int(self.config.get('mysql', 'port')),  # 端口，默认为3306
                db=self.config.get('mysql', 'db'),  # 数据库名称
                charset=self.config.get('mysql', 'charset'))


        except pymysql.Error as e:
            messagebox.showerror(title="警告", message=f"Error: {e}")
            print("Error: %s" % e)

#     关闭连接
    def close_conn(self):
        try:
            if self.conn:
                self.conn.close()
        except pymysql.Error as e:
            messagebox.showerror(title="警告", message=f"Error: {e}")
            print("Error: %s" % e)

    def get_userinfo(self):
        sql = 'SELECT * FROM b_user'

        # 使用cursor()方法获取操作游标
        cursor = self.conn.cursor()
        # 用execute执行sql
        cursor.execute(sql)
        # fetchall方法获取全部数据
        result = cursor.fetchall()
        #     将数据用字典的形式储存于result内
        result = [dict(zip([k[0] for k in cursor.description], row)) for row in result]

        cursor.close()
        # self.close_conn()
        return result

    def set_password(self,passwd = None,username = None):
        # sql = 'UPDATE b_user SET passwd=%s WHERE username=%s'
        # value = (passwd,username)
        # # 使用cursor()方法获取操作游标
        # cursor = self.conn.cursor()
        # # 用execute执行sql
        # cursor.execute(sql,value)
        # self.conn.commit()
        # cursor.close()
        self.close_conn()


def mainwindow(user = None,passwd=None):
    main_Window(user,passwd)




class Login():
    def __init__(self):

        self.root = Tk()
        self.root.title("")
        # self.root.iconbitmap(f"{ASSETS_PATH}/redo16x.ico")
        self.root.config(background="#2F2F2F")
        self.root.resizable(0, 0)
        root_height = 530
        root_width = 650
        sx = self.root.winfo_screenwidth()
        sy = self.root.winfo_screenheight()
        cw_x = (sx - root_width) / 2
        cw_y = (sy - root_height) / 2
        self.root.geometry("%dx%d+%d+%d" % (root_width, root_height, cw_x, cw_y))
        # photo3 = PhotoImage(file=relative_to_assets("redo16x.ico"))
        photo0 = PhotoImage(file=relative_to_assets("logochm.png"))
        photo1 = PhotoImage(file=relative_to_assets("OH_puma_icon.png"))
        self.photo2 = PhotoImage(file=relative_to_assets("jantu.png"))

        # 设置保存账号密码
        varPwd = StringVar(self.root, value='')
        varname = StringVar(self.root, value='')

        self.rememberMe = IntVar(self.root)

        # 用于记住密码这个模块读取文件

        try:
            self.config = configparser.ConfigParser()
            self.config.read_file(open(f"{OUTPUT_PATH}/NAMEANPASSWD.ini", encoding="utf-8", mode="rt"))
            ininame = self.config.get("HIKNAMEANDPASSWORD","username")
            inipasswd = self.config.get("HIKNAMEANDPASSWORD","password")
            inionoff = self.config.get("HIKNAMEANDPASSWORD","onoff")
            self.rememberMe.set(inionoff)
            varname.set(ininame)
            varPwd.set(inipasswd)
        except configparser.Error as e:
            messagebox.showerror(title="警告", message=f"Error: {e}")


        frame1 = Frame(self.root, bg="#2F2F2F", height=100, relief="flat")
        frame1.pack(side=TOP, fill=X)
        Label(frame1, text="HIK WMS 1.0", font=('微软雅黑', 20, 'bold'), fg="white", bg="#2F2F2F").grid(row=1, padx=25)
        Label(frame1, text="DESKTOP APPLICATION", font=('微软雅黑', 11, 'bold'), fg="white", bg="#2F2F2F").grid(row=2,
                                                                                                            padx=25)

        Label(frame1, width=34, bg="#2F2F2F").grid(row=1, column=3, rowspan=2)
        Label(frame1, image=photo0, bg="#2F2F2F").grid(row=1, column=4, rowspan=2)

        # frame0 = Frame(root,bg = "pink",relief = "flat",height = 100)
        # frame0.pack(anchor = "center",fill = X )
        Label(self.root, image=photo1, bg="#2F2F2F").pack(pady=25)

        frame2 = Frame(self.root, bg="#A1A1A1", relief="flat")
        frame2.pack(side=BOTTOM, fill=X)
        frame2_1 = Frame(frame2, bg="#A1A1A1", relief="flat")
        frame2_1.pack(side=BOTTOM)

        Label(frame2_1, text="欢迎登录WMS系统", font=("微软雅黑", 15, "bold"), fg="white", bg="#A1A1A1").grid(row=0, column=0,
                                                                                                    columnspan=2,
                                                                                                    pady=7)
        Label(frame2_1, text="账户:", font=('微软雅黑', 10, 'bold'), fg="white", bg="#A1A1A1").grid(row=1, column=0, padx=5,
                                                                                              pady=6)
        Label(frame2_1, text="密码:", font=('微软雅黑', 10, 'bold'), fg="white", bg="#A1A1A1").grid(row=2, column=0, padx=5,
                                                                                              pady=3)

        self.user = Entry(frame2_1,textvariable=varname, relief="flat", width=20, )
        self.user.grid(row=1, column=1, padx=5, pady=8)
        self.password = Entry(frame2_1,textvariable=varPwd ,relief="flat", width=20, show="*")
        self.password.grid(row=2, column=1, padx=5, pady=8)

        frame2_1_1 = Frame(frame2_1, bg="#A1A1A1", relief="flat",height = 20,width = 190)
        frame2_1_1.grid(row=3, column=0, columnspan=2)

        register_b = Checkbutton(frame2_1_1,text = "记住密码",relief="flat", width=6,bg = "#A1A1A1"
                                ,variable=self.rememberMe, onvalue=1,offvalue=0,fg = "#9ACDFA",activebackground = "#A1A1A1",bd = 0)
        register_b.grid(row = 0,column = 0)

        forgetpaas_b = Button(frame2_1_1, command = self.notpasswprd,text="找回密码", relief="flat",width=6, bg="#A1A1A1",fg = "#9ACDFA",activebackground = "#A1A1A1",bd = 0)
        forgetpaas_b.grid(row = 0,column = 2)
        Label(frame2_1_1,bg = "#A1A1A1",width = 10).grid(row = 0,column = 1)

        login_b = Button(frame2_1, text="登      录", relief="flat", width=26, command=self.login)
        login_b.grid(row=4, column=0, columnspan=2, padx=8, pady=5)



        self.password.bind("<Return>", self.login)
        # login_b.bind("<Return>", self.login)

        self.root.mainloop()

    def login(self,enter=""):
        self.obj = MysqlSearch()
        result = self.obj.get_userinfo()
        self.name = self.user.get()
        self.pwd = self.password.get()

        md5 = hashlib.md5(b"xx")  # 给密码加盐，加密
        md5.update(self.pwd.encode("utf-8"))
        self.str_md5 = md5.hexdigest()

        ulist = []
        plist = []
        mlist = []
        for item in result:
            ulist.append(item["username"])
            plist.append(item["passwd"])
            mlist.append(item['mailbox'])
        deter = True
        for i in range(len(ulist)):
            if self.name == ulist[i] or self.name == mlist[i]:
                if self.pwd == plist[i]:
                    # 密码哈希加密函数调用，因为跟记住密码功能冲突暂时注释
                    # self.obj.set_password(self.str_md5, self.name)
                    self.obj.set_password()
                    # deter1 = True
                    messagebox.showinfo(title="恭喜", message="登录成功")
                    # 用于记住密码模块设置保存密码或空值
                    if self.rememberMe.get() == 1:
                        self.config = configparser.ConfigParser()
                        self.config.add_section("HIKNAMEANDPASSWORD")
                        self.config.set("HIKNAMEANDPASSWORD", "username", self.name)
                        self.config.set("HIKNAMEANDPASSWORD", "password", plist[i])
                        self.config.set("HIKNAMEANDPASSWORD", "onoff", '1')
                        self.config.write(open(f"{OUTPUT_PATH}/NAMEANPASSWD.ini", 'w+', encoding="utf-8"))
                    else:
                        self.config = configparser.ConfigParser()
                        self.config.add_section("HIKNAMEANDPASSWORD")
                        self.config.set("HIKNAMEANDPASSWORD", "username", '')
                        self.config.set("HIKNAMEANDPASSWORD", "password", '')
                        self.config.set("HIKNAMEANDPASSWORD", "onoff", '0')
                        self.config.write(open(f"{OUTPUT_PATH}/NAMEANPASSWD.ini", 'w+', encoding="utf-8"))

                    deter = False
                    self.root.destroy()
                    mainwindow(user=ulist[i],passwd=self.pwd)
                elif self.str_md5 == plist[i]:
                    messagebox.showinfo(title="恭喜", message="登录成功")
                    # 用于记住密码模块设置保存密码或空值
                    if self.rememberMe.get() == 1:
                        self.config = configparser.ConfigParser()
                        self.config.add_section("HIKNAMEANDPASSWORD")
                        self.config.set("HIKNAMEANDPASSWORD", "username",self.name)
                        self.config.set("HIKNAMEANDPASSWORD", "password",self.str_md5)
                        self.config.set("HIKNAMEANDPASSWORD", "onoff",'1')
                        self.config.write(open(f"{OUTPUT_PATH}/NAMEANPASSWD.ini", 'w+',encoding="utf-8"))
                    else:
                        self.config = configparser.ConfigParser()
                        self.config.add_section("HIKNAMEANDPASSWORD")
                        self.config.set("HIKNAMEANDPASSWORD", "username", '')
                        self.config.set("HIKNAMEANDPASSWORD", "password", '')
                        self.config.set("HIKNAMEANDPASSWORD", "onoff", '0')
                        self.config.write(open(f"{OUTPUT_PATH}/NAMEANPASSWD.ini", 'w+', encoding="utf-8"))
                    deter = False
                    self.root.destroy()
                    mainwindow(user=ulist[i],passwd=self.pwd)
                    # mainwindow()
                else:
                    pass


            else:
                pass
        while deter:
            messagebox.showerror(title="警告", message="用户名或密码错误")
            break

    def notpasswprd(self):

        notpassword.Notpassword(self.root,self.photo2)

    # def regedit0(self):
    #     self.root.destroy()
    #     regedit.Ragedit()


if __name__ == "__main__":
    Login()